package com.cj.bigfileupload.controller;

import com.cj.bigfileupload.common.Response;
import com.cj.bigfileupload.common.enums.FileUploadStatusEnum;
import com.cj.bigfileupload.common.exception.BusinessException;
import com.cj.bigfileupload.controller.request.MultipartFileParam;
import com.cj.bigfileupload.controller.response.CheckMD5Res;
import com.cj.bigfileupload.service.IFileUploadService;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * ClassName: FileController <br/>
 * Function: 文件controller <br/>
 * date: 2018/05/08 15:33 <br/>
 *
 * @author chenj
 * @version 1.0.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping(value = "/file")
public class FileController {

    @Resource
    private IFileUploadService fileUploadService;

    /**
     * 秒传判断、断点判断
     *
     * @param md5
     * @return
     */
    @PostMapping(value = "/check-md5")
    public Response checkFile(String md5) throws IOException {
        // 不存在，则获取缓存数据，如果有缓存数据，则进行断点续传，没有则说明没有上传过
        String confFilePath = fileUploadService.getConfFilePathFromRedis(md5);
        // 存在conf文件，需要断点续传
        if (StringUtils.isNotEmpty(confFilePath)) {
            File confFile = new File(confFilePath);
            byte[] completeList = FileUtils.readFileToByteArray(confFile);
            List<String> missChunkList = new LinkedList<>();
            for (int i = 0; i < completeList.length; i++) {
                if (completeList[i] != Byte.MAX_VALUE) {
                    missChunkList.add(i + "");
                }
            }
            return Response.success(new CheckMD5Res(FileUploadStatusEnum.ING_HAVE, missChunkList));
        }
        // 不存在，通知调用者不存在，需要重新上传
        return Response.success(new CheckMD5Res(FileUploadStatusEnum.NO_HAVE));
    }

    /**
     * 上传文件
     *
     * @param fileParam
     * @param request
     * @throws IOException
     */
    @PostMapping(value = "/upload")
    public Response upload(MultipartFileParam fileParam, HttpServletRequest request) {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            throw new BusinessException("error.fileupload.multipart");
        }
        fileUploadService.uploadFile(fileParam);
        return Response.success();
    }
}
